package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Function;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Login;
import com.smcdd.cdb.dbo.cdb_dbo.service.exception.ApiException;
import com.smcdd.cdb.dbo.cdb_dbo.service.exception.MyObserver;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.DataManager;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.ILoginAc;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.MainActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BasePresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.IsMobileNO;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.SystemUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 作者：Administrator on 2017/6/26 13:06
 * 邮箱：zhanghuaiha@gmail.com
 */

public class LoginPresenter extends BasePresenter<ILoginAc> {

    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private boolean mobileNO;
    private TextView tv;
    private EditText telET;
    private String code = "";
    private EditText etCode;
    private TextView login;
    private boolean flag;
    private String versionCode;

    public LoginPresenter(BaseActivity context) {
        super(context);
    }

    public void loadContacts(){
        manager = new DataManager(mContext);
        mCompositeSubscription = new CompositeSubscription();
        versionCode = ObtainVersion.getVersionName(mContext);
        setAdapter();
    }

    private void setAdapter() {

    }

    public void unLoadData(){
        if (mCompositeSubscription.hasSubscriptions()){
            mCompositeSubscription.unsubscribe();
        }
    }


    public void getTel2Code(String udid){
        telET = getView().getTelET();
        etCode = getView().getETCode();
        tv = getView().getTV();
        login = getView().getLogin();
        //判断手机号是否正确
        telET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //判断手机号格式是否正确
                mobileNO = IsMobileNO.isMobileNO(s.toString());
                if (mobileNO) {
                    tv.setTextColor(Color.parseColor("#32C340"));
                }else {
                    tv.setTextColor(Color.parseColor("#60000000"));
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        tv.setOnClickListener(v -> {
            if (mobileNO) {
                countDownTimer.start();
                loadData(udid);
            }else {

            }
        });

        //判断验证码是否正确
        etCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(s.toString().length()==4){
                    flag = true;
                    login.setTextColor(Color.parseColor("#32C340"));
                }else {
                    login.setTextColor(Color.parseColor("#60000000"));
                    flag = false;
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        login.setOnClickListener(v -> {
            if (flag) {
                initDateS(udid);
            }
        });
    }

    CountDownTimer countDownTimer = new CountDownTimer(90*1000,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            tv.setText("再次获取("+millisUntilFinished/1000+"s)");
            mobileNO = false;
            tv.setTextColor(Color.parseColor("#60000000"));
        }

        @Override
        public void onFinish() {
            tv.setText("获取验证码");
            mobileNO = true;
            tv.setTextColor(Color.parseColor("#32C340"));
        }
    };

    private void initDateS(String udid) {
        String tel = App.SP.getString("tel", "");
        String time = System.currentTimeMillis() + "";
        String encry = ObtainEncry.getCode("2", time, versionCode, NetWorkCodeInfo.TEL, udid, telET.getText().toString());
        manager.getDemo("2",time,versionCode, NetWorkCodeInfo.TEL,udid,telET.getText().toString(),encry).subscribe(new MyObserver<BaseResponseEntity>() {
            @Override
            protected void onError(ApiException ex) {
                Log.e("tel",ex.getMessage());
            }

            @Override
            public void onCompleted() {
            }

            @Override
            public void onNext(BaseResponseEntity baseResponseEntity) {
                if (baseResponseEntity.code == 200) {
                    login(udid);
                }else {
                    ToastUtil.showToast(baseResponseEntity.message);
                }
            }
        });

    }



    //获取验证码 网络请求
    public void loadData(String udid) {
        String time = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",time);
        map.put("v",versionCode);
        map.put("i",NetWorkCodeInfo.CODE);
        map.put("udid",udid);
        map.put("mobile",telET.getText().toString());
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getCode(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<String>>() {
                    @Override
                    public void success(BaseResponseEntity<String> listBaseResponseEntity) {
                        if (listBaseResponseEntity.code == 200) {
                            code = listBaseResponseEntity.data;
                        }else {
                            ToastUtil.showToast(listBaseResponseEntity.message);
                        }
                    }
                });
    }

    //登录
    public void login(String udid) {
        String time = System.currentTimeMillis() + "";
        String brand = SystemUtil.getDeviceBrand();
        String model = SystemUtil.getSystemModel();
        String version_release = SystemUtil.getSystemVersion();
        String models = model.replaceAll(" ", "-");
        String versionCode = ObtainVersion.getVersionName(mContext);
        String encry = ObtainEncry.login("2",time,versionCode, NetWorkCodeInfo.LOGIN,udid,telET.getText().toString(),code,"2",brand,telET.getText().toString(),models,version_release,"0");
        RetrofitFactory.getmInstanse().mApi.login("2",time,versionCode, NetWorkCodeInfo.LOGIN,udid,telET.getText().toString(),code,"2",brand,telET.getText().toString(),models,version_release,"0",encry)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<Login>>() {
                    @Override
                    public void success(BaseResponseEntity<Login> loginBaseResponseEntity) {
                        if (loginBaseResponseEntity.code == 200) {
                            Login login = loginBaseResponseEntity.data;
                            App.EDIT.putString("tel", login.getMobile());
                            App.EDIT.putString("id", login.getId());
                            App.EDIT.putString("old_id", login.getId());
                            App.EDIT.putString("oid", (String)login.getOrganization_id());
//                            App.EDIT.putString("id", "20");
//                            App.EDIT.putString("old_id", "20");
//                            App.EDIT.putString("oid", "48");
                            App.EDIT.putString("user", login.getName());
                            App.EDIT.putString("tel", login.getMobile());
                            App.EDIT.commit();
                            mContext.jumpToActivity(MainActivity.class);
                            mContext.finish();
                        }else {
                            ToastUtil.showToast(loginBaseResponseEntity.message);
                        }
                    }
                });
    }
}
